<template>
  <!-- 分时策略模板明细 -->
  <a-modal :width="1200" v-model:visible="showPolicyItemDetail" :footer="false" :title="`策略应用明细-${PolicyType[currentData.policyType]}`" title-align="start" :mask-closable="false" @cancel="closedDialog">
    <a-form style="margin-bottom: 10px" ref="formRef" :model="currentData">
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item field="policyName" label="策略名称：" label-col-flex="100px">
            <p>{{ currentData.policyName }}</p>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="生效日期：" label-col-flex="100px">
            <p v-if="!currentData.effectiveEndDate && !currentData.effectiveStartDate">一直有效</p>
            <p v-else>{{ currentData.effectiveStartDate }}~{{ currentData.effectiveEndDate }}</p>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item field="isShare" label="是否共享：" label-col-flex="100px">
            <p>{{ currentData.isShare === 1 ? '共享' : '不共享' }}</p>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="marketplaceIds" label="适用站点：" label-col-flex="100px">
            <p>{{ getMarketplace(currentData.applicableMarketplace) }}</p>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item field="isShare" :label="`原始${PolicyTypeText[currentData.policyType]}：`" label-col-flex="100px">
            <p>
              <span style="margin-right: 10px">{{ PolicyOriginType[currentData.budgetType] }}</span>
              <span class="highlight" v-if="currentData.budgetType === 'FIXED_BUDGET'">$ {{ currentData.fixedBudgetAmount }}</span>
            </p>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="marketplaceIds" label="调整频率：" label-col-flex="100px">
            <PolicyRuleDetail className="text-limit" :policyType="currentData.policyType" :detail="currentData" :ruleList="currentData.policyTemplateRuleDOS" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-item field="isShare" :label="`${PolicyTypeText[currentData.policyType]}回调：`" label-col-flex="100px">
            <p v-if="currentData.isPolicyCallback === 2">不回调</p>
            <p v-else>
              <span style="margin-right: 10px">生效时间结束后，将每个对象的{{ PolicyTypeText[currentData.policyType] }}调整为</span>
              <!-- 竞价和预算 -->
              <template v-if="currentData.policyType == 'BUDGET_POLICY' || currentData.policyType == 'BIDDING_POLICY'">
                <span style="margin-right: 5px">{{ currentData.isPolicyCallback === 0 ? '基准值' : '固定值' }}</span>
                <span class="highlight">$ {{ currentData.fixedCallbackAmount }}</span>
              </template>
              <!-- 状态 -->
              <template v-else-if="currentData.policyType == 'SWITCH_POLICY'">
                <span style="margin-right: 5px">{{ currentData.isPolicyCallback === 0 ? '原始状态' : '固定状态' }}</span>
                <span v-if="currentData.isPolicyCallback === 1" class="highlight">{{ currentData.fixedCallbackValue === 'ENABLED' ? '启用' : '暂停' }}</span>
              </template>
              <!-- 广告位 -->
              <template v-else-if="currentData.policyType == 'TARGETING_POLICY'">
                <span style="margin-right: 5px">原价</span>
              </template>
            </p>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <a-form style="margin-bottom: 5px" :model="searchVal" layout="inline" size="medium">
      <a-form-item hide-label>
        <a-select style="width: 140px" v-model="searchVal.shopIds" placeholder="店铺" allow-clear @change="searchByVal">
          <a-option v-for="shop in shopList" :key="shop.value" :value="shop.value" :label="shop.label" />
        </a-select>
      </a-form-item>
      <a-form-item hide-label>
        <a-select style="width: 100px" v-model="searchVal.adType" placeholder="广告类型" allow-clear @change="searchByVal">
          <a-option value="SPONSORED_PRODUCTS" label="商品广告" />
          <a-option value="SPONSORED_BRANDS" label="品牌广告" />
          <a-option value="SPONSORED_DISPLAY" label="展示广告" />
        </a-select>
      </a-form-item>
      <a-form-item hide-label>
        <a-input-search v-model="searchVal.campaignName" style="width: 140px" size="small" placeholder="广告活动" allow-clear @press-enter="searchByVal" @clear="getTableList" @search="getTableList" />
      </a-form-item>
      <a-form-item hide-label>
        <a-select style="width: 140px" v-model="searchVal.state" placeholder="策略应用状态" allow-clear @change="searchByVal">
          <a-option :value="1" label="开启" />
          <a-option :value="0" label="暂停" />
        </a-select>
      </a-form-item>
      <a-form-item hide-label>
        <a-input-search v-model="searchVal.policyApplicationName" size="small" style="width: 140px" placeholder="应用对象名称" allow-clear @press-enter="searchByVal" @clear="searchByVal" @search="searchByVal" />
      </a-form-item>
    </a-form>
    <div class="handle-btns">
      <a-space>
        <a-button type="primary" v-if="$authPass('policy-targeting.batch.save')" size="medium" @click="showAddPolicyItem = true">添加</a-button>
        <a-button class="gray-outline" v-if="$authPass('policy-targeting.operation')" size="medium" @click="changeStateBatch(0, '暂停')">暂停</a-button>
        <a-button class="gray-outline" v-if="$authPass('policy-targeting.operation')" size="medium" @click="changeStateBatch(2, '移除')">移除</a-button>
        <a-button class="gray-outline" v-if="$authPass('policy-targeting.operation')" size="medium" @click="changeStateBatch(1, '开启')">开启</a-button>
      </a-space>
    </div>
    <div class="table-model-wrap" style="margin-top: 5px">
      <a-table class="table-two-line" ref="tableRef" row-key="id" :loading="tableLoading" @selection-change="selectColumn" :row-selection="rowSelection" :bordered="false" :data="tableList" :scroll="{ y: 'calc(84vh - 360px)' }" size="mini" :pagination="false">
        <template #columns>
          <a-table-column title="策略状态" :width="80">
            <template #cell="{ record }">
              <a-popconfirm :content="`确定是否${record.state === 0 ? '开启' : '暂停'}策略`" @ok="changeState(record)" type="warning">
                <a-switch :disabled="!$authPass('policy-targeting.operation')" v-model="record.state" :checked-value="1" :unchecked-value="0" style="margin-right: 5px" :beforeChange="handleChangeIntercept" />
              </a-popconfirm>
            </template>
          </a-table-column>
          <a-table-column title="应用对象">
            <template #cell="{ record }">
              <p>{{ TargetingType[record.targetingType] || '--' }}</p>
              <!-- 非竞价模板显示广告活动名称 -->
              <p v-if="currentData.policyType != 'BIDDING_POLICY'">{{ record.campaignName || '--' }}</p>
              <!-- 竞价类型显示关键词或商品 -->
              <p v-else>{{ record.keywordText || record.targetingResolvedExpressionValue || '--' }}</p>
            </template>
          </a-table-column>
          <a-table-column title="店铺" :width="120" data-index="shopName" :ellipsis="true" :tooltip="true" />

          <a-table-column title="广告类型" :width="80">
            <template #cell="{ record }">
              <p>{{ AdTypes[record.adType] }}</p>
            </template>
          </a-table-column>
          <a-table-column title="广告活动" data-index="campaignName" :ellipsis="true" :tooltip="true" />
          <a-table-column title="广告组" v-if="currentData.policyType == 'BIDDING_POLICY'" data-index="adGroupName" :ellipsis="true" :tooltip="true" />
          <a-table-column title="基准预算/竞价" :width="100">
            <template #cell="{ record }">
              <p>${{ record.campaignBudgetAmount }}</p>
              <p>${{ record.referenceAmount }}</p>
            </template>
          </a-table-column>
          <a-table-column title="添加人" :width="70" data-index="createUserName" />
          <a-table-column title="添加时间" :width="140">
            <template #cell="{ record }">
              <p>{{ $setTime(record.gmtCreate) }}</p>
            </template>
          </a-table-column>
          <a-table-column title="操作" :width="80">
            <template #cell="{ record }">
              <a-popconfirm content="确定是否移除策略?" @ok="deleteItem(record)" type="error">
                <a-button v-if="$authPass('policy-targeting.operation')" type="text">移除</a-button>
              </a-popconfirm>
            </template>
          </a-table-column>
        </template>
      </a-table>
    </div>
    <div class="pagination-footer" style="margin-top: 10px">
      <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
    </div>
    <!-- 添加分时策略明细 -->
    <AddPolicyItem v-if="showAddPolicyItem" :shopList="shopList" :currentData="currentData" :isShow="showAddPolicyItem" @closed="showAddPolicyItem = false" @success="getTableList" />
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted, reactive, PropType } from 'vue'
  import { PolicyType, PolicyBudgetType, PolicyBidType, PolicyTypeText, TargetingType, AdTypes } from '../../types'
  import { marketPlaceList } from '@/utils/globalData'
  import { getPolicyList, operationPolicyTargeting } from '@/api/advert'
  import { Message, Modal } from '@arco-design/web-vue'
  import AddPolicyItem from './addPolicyItem.vue'
  import PolicyRuleDetail from './policyRuleDetail.vue'

  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    shopList: {
      type: Array as PropType<Array<any>>,
      default: () => [],
    },
    currentData: {
      type: Object,
      default: () => {},
    },
  })
  onMounted(async () => {
    getTableList()
  })

  const showPolicyItemDetail = ref(props.isShow)
  const searchVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
  })
  const PolicyOriginType = props.currentData.policyType === 'BIDDING_POLICY' ? PolicyBidType : PolicyBudgetType
  const total = ref(0)
  const showAddPolicyItem = ref(false)
  const tableLoading = ref(false)
  const tableList = ref([])
  const selectIds = ref([])
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any

  function selectColumn(val: any) {
    selectIds.value = val
  }
  // 显示站点名称
  function getMarketplace(marketplaces: string) {
    let arr = marketplaces?.split(',')
    let names = arr?.map((val: string) => marketPlaceList[val]?.code)
    return names?.join(',')
  }
  //产品列表数据
  async function getTableList() {
    let _params = JSON.parse(JSON.stringify(searchVal.value))
    _params.shopIds = _params.shopIds ? [_params.shopIds] : null
    _params.policyId = props.currentData.id
    tableLoading.value = true
    const res: any = await getPolicyList(_params)
    tableLoading.value = false
    tableList.value = res?.data?.data || []
    total.value = res?.data?.total || 0
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }
  // 通过条件查询用户列表
  function searchByVal() {
    searchVal.value.pageNum = 1
    getTableList()
  }
  // 关闭
  function closedDialog() {
    showPolicyItemDetail.value = false
    emit('closed')
  }
  // 拦截自动切换
  async function handleChangeIntercept() {
    return false
  }
  // 单个切换状态
  async function changeState(row: any) {
    let state = row.state === 0 ? 1 : 0
    let res: any = await operationPolicyTargeting({
      policyTargetingIds: [row.id],
      state: state,
    })
    if (res) {
      getTableList()
    }
  }
  // 批量更改
  function changeStateBatch(status: number, statusText: string) {
    if (!selectIds.value.length) {
      return Message.error('请选择应用明细')
    }
    Modal.confirm({
      title: '提示',
      content: `请再次确认，${statusText}选中的分时应用明细`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: async () => {
        let res: any = await operationPolicyTargeting({
          policyTargetingIds: selectIds.value,
          state: status,
        })
        if (res) {
          Message.success(`${statusText}成功`)
          getTableList()
        }
      },
    })
  }
  // 删除
  async function deleteItem(row: any) {
    let res: any = await operationPolicyTargeting({
      policyTargetingIds: [row.id],
      state: 2,
    })
    if (res) {
      getTableList()
    }
  }
</script>
<style lang="less" scoped>
  .arco-form-item {
    margin-bottom: 5px;
    margin-right: 10px;
  }
</style>
